/**
 * Created by zheng on 2019/1/3.
 */




export default {
  name: 'ZgMeteor',
  props: {
    height: {
      type: Number,
      default: 30
    },
    width: {
      type: Number,
      default: 30
    },
  },
  data(){
    return {
      points: [],
      edges: [],
      ctx: null,
      canvas: null,
      count: 0
    }
  },
  mounted(){

    this.init()
    this.loop()
  },
  render(h){
    return (<canvas ref={"lazer"} width={this.width} height={this.height}></canvas>)
  },
  methods: {
    loop() {
      this.updatePoints()
      if (this.count > 50) {
        this.count = 0
        this.points.push(this.createPoint())
      }
      else this.count++
      window.requestAnimationFrame(this.loop);
    },
    updatePoints() {
      let canvas = this.$refs.lazer
      if(!canvas){
        return
      }

      let ctx = canvas.getContext('2d');
      ctx.clearRect(0, 0, canvas.width, canvas.height)
      this.points.forEach((point) => {
        if (point.alpha < 1) point.alpha += 0.01
        let beforePointX = point.x - 200 * point.directX * point.speed
        let beforePointY = point.y - 200 * point.directY * point.speed
        point.x += point.directX * point.speed
        point.y += point.directY * point.speed
        ctx.beginPath();
        ctx.moveTo(point.x, point.y)
        // ctx.fillStyle = `rgba(200,200,200,${point.alpha})`;
        ctx.fillStyle = `rgba(${point.color.r},${point.color.g},${point.color.b},${point.alpha})`;
        ctx.shadowColor = `white`;
        ctx.shadowBlur = 30
        ctx.alpha = point.alpha
        ctx.arc(point.x, point.y, 2, 0, 2 * Math.PI)
        ctx.fill()
        ctx.beginPath();
        ctx.moveTo(point.x, point.y)
        ctx.lineTo(beforePointX, beforePointY)
        let grad = ctx.createLinearGradient(point.x, point.y, beforePointX, beforePointY)
        grad.addColorStop(0, `rgba(${point.color.r},${point.color.g},${point.color.b}, 1)`)
        grad.addColorStop(1, `rgba(255,255,255,0)`)
        ctx.strokeStyle = grad
        ctx.lineWidth = 3
        ctx.stroke()
      })
    },
    isInRect(point){
      let canvas = this.$refs.lazer
      if (point.x >= 0 && point.x <= canvas.width && point.y >= 0 && point.y <= canvas.height)
        return true
      return false
    },
    init() {
      for (let i = 0; i < 20; i++) {
        this.points.push(this.createPoint())
      }
    },
    createPoint(){
      let point = {}
      point.x = this.width * Math.random();
      point.y = this.height * Math.random();
      point.color = {};
      point.status = 0
      point.color.r = Math.floor(255 * Math.random())
      point.color.g = Math.floor(255 * Math.random())
      point.color.b = Math.floor(255 * Math.random())
      point.directX = 2 * Math.random() - 1
      point.directY = 2 * Math.random() - 1
      point.speed = 1 + 2 * Math.random()
      point.alpha = 0.1
      return point
    }
  },
}
